import { createGridView, boundField, customField } from "myWuZhui";
// import app from "admin/application";
import { MemberService } from "admin/services/member";
import { siteMap } from "admin/pageNodes";
import { FormValidator, rules as r } from "maishu-dilu";
import React = require("react");
import ReactDOM = require("react-dom");
import { UserService } from "admin/services/user";
import * as wuzhui from "maishu-wuzhui";
import * as chitu from "maishu-chitu";
import { PageProps } from "maishu-chitu-react";

let w = wuzhui;
// export default function (page: chitu.Page) {
//     ReactDOM.render(<RoleListPage />, page.element);
// }

interface State {
    role: Role
}

export default class RoleListPage extends React.Component<PageProps, State>{
    roleDialog: HTMLElement;
    rolesTable: HTMLTableElement;
    validator: FormValidator;
    dataSource: wuzhui.DataSource<Role>;

    constructor(props) {
        super(props);
        this.state = { role: {} as Role }
    }
    showDialog(role?: Role) {
        if (role) {
            this.setState({ role })
        }
        ui.showDialog(this.roleDialog);
    }
    save() {
        if (!this.validator.check())
            return

        let { role } = this.state
        if (role.id) {
            return this.dataSource.update(role)
        }

        let q: Promise<any> = role.id ? this.dataSource.update(role) : this.dataSource.insert(role)
        q.then(() => {
            ui.hideDialog(this.roleDialog)
        })
        return q
    }
    componentDidMount() {
        let station = this.props.app.createService(UserService);
        this.dataSource = new w.DataSource({
            primaryKeys: ['id'],
            async select() {
                let dataItems = await station.roles();
                return { dataItems, totalRowCount: dataItems.length };
            },
            update(dataItem) {
                return station.updateRole(dataItem)
            },
            insert(dataItem: Role) {
                return station.addRole(dataItem.name, dataItem.remark)
            },
            delete(dataItem) {
                return station.removeRole(dataItem.id)
            }
        })

        let it = this
        createGridView({
            dataSource: this.dataSource,
            element: this.rolesTable,
            columns: [
                boundField<Role>({ dataField: 'name', headerText: '名称' }),
                boundField<Role>({ dataField: 'remark', headerText: '备注' }),
                customField({
                    createItemCell(dataItem: Role) {
                        let cell = new wuzhui.GridViewCell();
                        ReactDOM.render(<React.Fragment>
                            <button className="btn btn-info btn-minier" style={{ marginRight: 4 }}
                                onClick={() => it.showDialog(dataItem)}>
                                <i className="icon-pencil"></i>
                            </button>
                            <button className="btn btn-minier btn-danger" style={{ marginRight: 4 }}
                                ref={(e: HTMLElement) => {
                                    if (!e) return;
                                    e.onclick = ui.buttonOnClick(() => it.dataSource.delete(dataItem),
                                        { confirm: `确定要删除'${dataItem.name}'角色` });
                                }}>
                                <i className="icon-trash"></i>
                            </button>
                            <button className="btn btn-info btn-minier" style={{ marginRight: 4 }}
                                onClick={() => it.props.app.redirect(siteMap.nodes.member_role.name, { roleId: dataItem.id })}>
                                <span>设置权限</span>
                            </button>

                        </React.Fragment>, cell.element)
                        return cell
                    },
                    headerStyle: { width: '160px', textAlign: 'center' } as CSSStyleDeclaration,
                    headerText: '角色',
                    itemStyle: { textAlign: 'center' } as CSSStyleDeclaration,
                })
            ]
        })
        this.validator = new FormValidator(this.roleDialog,
            { name: 'name', rules: [r.required('请输入角色名称')] }
        )
    }
    render() {
        let { role } = this.state
        return <React.Fragment>
            <ul key={10}>
                <li className="pull-right">
                    <button className="btn btn-sm btn-primary"
                        onClick={() => this.showDialog()}>
                        <i className="icon-plus" />
                        <span>添加角色</span>
                    </button>
                </li>
            </ul>
            <table key={20} ref={(e: HTMLTableElement) => this.rolesTable = e || this.rolesTable}></table>
            <div key={30} className="modal fade"
                ref={(e: HTMLElement) => this.roleDialog = e || this.roleDialog}>
                <div className="modal-dialog">
                    <div className="modal-content">
                        <div className="modal-header">
                            <button type="button" className="close"
                                onClick={() => ui.hideDialog(this.roleDialog)}>
                                <span aria-hidden="true">&times;</span>
                            </button>
                            <h4 className="modal-title">添加角色</h4>
                        </div>
                        <div className="modal-body form-horizontal">
                            <div className="form-group">
                                <label className="col-sm-2 control-label">名称*</label>
                                <div className="col-sm-10">
                                    <input name="name" type="text" className="form-control"
                                        placeholder="请输入角色名称"
                                        value={role.name || ''}
                                        onChange={e => {
                                            role.name = (e.currentTarget as HTMLInputElement).value;
                                            this.setState({ role })
                                        }} />
                                </div>
                            </div>
                            <div className="form-group">
                                <label className="col-sm-2 control-label">备注</label>
                                <div className="col-sm-10">
                                    <input name="name" type="text" className="form-control"
                                        placeholder="请输入备注"
                                        value={role.remark || ''}
                                        onChange={e => {
                                            role.remark = (e.currentTarget as HTMLInputElement).value;
                                            this.setState({ role })
                                        }} />
                                </div>
                            </div>
                        </div>
                        <div className="modal-footer">
                            <button name="cancel" type="button" className="btn btn-default"
                                onClick={() => ui.hideDialog(this.roleDialog)}>
                                取消
                            </button>
                            <button name="ok" type="button" className="btn btn-primary"
                                ref={(e: HTMLButtonElement) => {
                                    ui.buttonOnClick(e, () => this.save())
                                }}>
                                确定
                            </button>
                        </div>
                    </div>
                </div>
            </div>


        </React.Fragment>
    }
}